package com.neusoft.neuiotms.dcom.controller.malfunction;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.file.dto.FileDTO;
import com.neusoft.bizcore.file.service.FileService;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionApplyFormDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionCountersignatureApprovalDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionCustomerReviewDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionFrontlineProcessingFormDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionLeaderApprovalDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionSecondLeaderDTO;
import com.neusoft.neuiotms.dcom.dto.malfunction.MalfunctionSecondLineDTO;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionApplyFormService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionCountersignatureApprovalService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionCustomerReviewService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionFrontlineProcessingFormService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionLeaderApprovalService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionSecondLeaderService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionSecondLineService;
import com.neusoft.neuiotms.dcom.service.malfunction.MalfunctionService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "故障管理")
@RestController
@RequestMapping(value = "/api/w/malfunction")
public class MalfunctionController {

    @Autowired
    private MalfunctionApplyFormService applyFormService;
    @Autowired
    private MalfunctionFrontlineProcessingFormService malfunctionFrontlineProcessingFormService;
    @Autowired
    private MalfunctionLeaderApprovalService leaderApprovalService;
    @Autowired
    private MalfunctionCustomerReviewService customerReviewService;
    @Autowired
    private MalfunctionSecondLineService secondLineService;
    @Autowired
    private MalfunctionCountersignatureApprovalService countersignatureApprovalService;
    @Autowired
    private MalfunctionSecondLeaderService secondLeaderService;
    @Autowired
    private FileService fileService;
    @Autowired
    private MalfunctionService malfunctionService;

    @ApiOperation("新增故障申请表单")
    @PostMapping("/applyform")
    public ResultDTO<MalfunctionApplyFormDTO> create(@RequestBody final MalfunctionApplyFormDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.applyFormService.create(dto, user));
    }

    @ApiOperation("查看故障申请表单")
    @GetMapping("/applyform/{workNum}/{taskId}")
    public ResultDTO<MalfunctionApplyFormDTO> details(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.applyFormService.detail(workNum, taskId, user));
    }

    @ApiOperation("申请annex上传文件")
    @PostMapping("applyform/upload/annex")
    public ResultDTO<FileDTO> applyformUpload(@RequestParam("file") final MultipartFile file) {
        final FileDTO doc = this.applyFormService.save(file);
        return ResultDTO.success(doc);
    }

    @ApiOperation("申请annex下载文件")
    @GetMapping("applyform/download/annex/{fsId}")
    public void applyformDownload(@PathVariable final String fsId, final HttpServletResponse response) {
        this.fileService.download(fsId, response);
    }

    @ApiOperation("申请annex删除文件")
    @DeleteMapping("applyform/annex/{fsId}")
    public void applyformDeleteAttachments(@PathVariable final String fsId) {
        this.applyFormService.deleteMongoFile(fsId);
    }

    @ApiOperation("新增故障处理表单")
    @PostMapping("/frontlineProcessingForm")
    public ResultDTO<MalfunctionFrontlineProcessingFormDTO> create(
            @RequestBody final MalfunctionFrontlineProcessingFormDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.malfunctionFrontlineProcessingFormService.create(dto, user));
    }

    @ApiOperation("查看故障处理表单")
    @GetMapping("/frontlineProcessingForm/{workNum}/{taskId}")
    public ResultDTO<MalfunctionFrontlineProcessingFormDTO> frontlineProcessingDetails(
            @PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.malfunctionFrontlineProcessingFormService.detail(workNum, taskId, user));
    }

    @ApiOperation("新增组长审批意见")
    @PostMapping("/leaderapproval")
    public ResultDTO<MalfunctionLeaderApprovalDTO> create(@RequestBody final MalfunctionLeaderApprovalDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.leaderApprovalService.create(dto, user));
    }

    @ApiOperation("查看组长审批意见")
    @GetMapping("/leaderapproval/{workNum}/{taskId}")
    public ResultDTO<MalfunctionLeaderApprovalDTO> leaderApprovalDetails(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.leaderApprovalService.detail(workNum, taskId, user));
    }

    @ApiOperation("新增二线领导确认")
    @PostMapping("/secondLeader")
    public ResultDTO<MalfunctionSecondLeaderDTO> secondLeaderCreate(@RequestBody final MalfunctionSecondLeaderDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.secondLeaderService.create(dto, user));
    }

    @ApiOperation("查看二线领导确认")
    @GetMapping("/secondLeader/{workNum}/{taskId}")
    public ResultDTO<MalfunctionSecondLeaderDTO> secondLeaderDetails(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.secondLeaderService.detail(workNum, taskId, user));
    }

    @ApiOperation("新增二线处理")
    @PostMapping("/secondLine/{type}")
    public ResultDTO<MalfunctionSecondLineDTO> secondLineCreate(@RequestBody final MalfunctionSecondLineDTO dto,
            @PathVariable final String type,
            final UserBean user) {
        return ResultDTO.success(this.secondLineService.create(dto, type, user));
    }

    @ApiOperation("查看二线处理")
    @GetMapping("/secondLine/{workNum}/{taskId}")
    public ResultDTO<MalfunctionSecondLineDTO> secondLineDetails(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.secondLineService.detail(workNum, taskId, user));
    }

    @ApiOperation("新增会签节点处理")
    @PostMapping("/countersignature")
    public ResultDTO<MalfunctionCountersignatureApprovalDTO> countersignatureCreate(
            @RequestBody final MalfunctionCountersignatureApprovalDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.countersignatureApprovalService.create(dto, user));
    }

    @ApiOperation("查看会签节点处理")
    @GetMapping("/countersignature/{workNum}/{taskId}")
    public ResultDTO<MalfunctionCountersignatureApprovalDTO> countersignatureDetails(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.countersignatureApprovalService.detail(workNum, taskId, user));
    }

    @ApiOperation("新增客户评价")
    @PostMapping("/customerreview")
    public ResultDTO<MalfunctionCustomerReviewDTO> customerReviewCreate(
            @RequestBody final MalfunctionCustomerReviewDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.customerReviewService.create(dto, user));
    }

    @ApiOperation("查看客户评价")
    @GetMapping("/customerreview/{workNum}/{taskId}")
    public ResultDTO<MalfunctionCustomerReviewDTO> customerReviewDetails(@PathVariable final String workNum,
            @PathVariable final String taskId,
            final UserBean user) {
        return ResultDTO.success(this.customerReviewService.detail(workNum, taskId, user));
    }

    @ApiOperation("annex上传文件")
    @PostMapping("customerreview/upload/annex")
    public ResultDTO<FileDTO> upload(@RequestParam("file") final MultipartFile file) {
        final FileDTO doc = this.customerReviewService.save(file);
        return ResultDTO.success(doc);
    }

    @ApiOperation("annex下载文件")
    @GetMapping("customerreview/download/annex/{fsId}")
    public void download(@PathVariable final String fsId, final HttpServletResponse response) {
        this.fileService.download(fsId, response);
    }

    @ApiOperation("annex删除文件")
    @DeleteMapping("customerreview/annex/{fsId}")
    public void deleteAttachments(@PathVariable final String fsId) {
        this.customerReviewService.deleteMongoFile(fsId);
    }

    @ApiOperation("处理故障工单统计")
    @GetMapping("/audit/handle")
    public ResultDTO<?> auditHandleMalfunctionNum(final UserBean user) {
        final long total = this.malfunctionService.countOfFinishedMalfunction(user);
        return ResultDTO.success(total);
    }

    @ApiOperation("协办故障工单统计")
    @GetMapping("/audit/sponsor")
    public ResultDTO<?> auditCoSponsorMalfunctionNum(final UserBean user) {
        final int total = this.malfunctionService.auditCoSponsorMalfunctionNumByUser(user);
        return ResultDTO.success(total);
    }

    @ApiOperation("故障服务统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<?> reportStats(final Pageable pageable, @RequestParam final Map<String, Object> params) {
        final Page<Map<String, Object>> result = this.malfunctionService.report(pageable, params);
        return PageResultDTO.success(result);
    }

    @ApiOperation("故障服务统计报表")
    @GetMapping(value = "/stats/export")
    public void exportStats(@RequestParam final Map<String, Object> params,
            final HttpServletResponse response) {

        final Workbook workbook = this.malfunctionService.exportReport(params);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("故障服务统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            MalfunctionController.log.error("故障服务统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                MalfunctionController.log.error("故障服务统计导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("导出故障工单")
    @GetMapping(value = "/export/{worknum}")
    public void downloadWord(@PathVariable final String worknum, final HttpServletResponse response) {

        final XWPFDocument xfc = this.malfunctionService.export(worknum);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("项目服务月报" + LocalDateTime.now() + ".docx", "UTF-8")));
            xfc.write(out);
            out.flush();
        } catch (final Exception e) {
            MalfunctionController.log.error("故障工单导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                MalfunctionController.log.error("故障工单导出关闭流失败", e);
            }
        }
    }
}
